package com.example.agrigreennewssys.service.impl;

import com.example.agrigreennewssys.dao.*;
import com.example.agrigreennewssys.dto.ArticleDetailDTO;
import com.example.agrigreennewssys.entity.*;
import com.example.agrigreennewssys.lucene.LuceneIndexService;
import com.example.agrigreennewssys.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author 光的代言人
 */
@Service("articleService")
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private ArticleLikeMapper articleLikeMapper;
    @Autowired
    private UserProfileMapper userProfileMapper;


    @Autowired
    private LuceneIndexService luceneIndexService;

    /**
     * 创建文章
     *
     * @param article
     * @return
     */
    @Transactional
    @Override
    public Article createArticle(Article article) {
        // 验证标签是否存在
        if (article.getTagId() != null) {
            Tag tag = tagMapper.selectTagById(article.getTagId());
            if (tag == null) {
                throw new RuntimeException("标签不存在");
            }
        }

        // 设置创建时间
        article.setCreatedAt(String.valueOf(new Date()));
        article.setUpdatedAt(String.valueOf(new Date()));

        articleMapper.insertArticle(article);
        String tagName=tagMapper.selectNameById(article.getTagId());

        UserProfile userProfile=userProfileMapper.findUserProfileByUserId(article.getAuthorId());
        // 创建索引
        try {
            // 5. 获取完整聚合数据（文章 + 用户 + 标签）
            ArticleDetailDTO homeArticle = new ArticleDetailDTO();
            homeArticle.setArticleId(article.getId());
            homeArticle.setNickName(userProfile.getNickName());
            homeArticle.setAvatarUrl(userProfile.getAvatarUrl());
            homeArticle.setCreatedAt(article.getCreatedAt());
            homeArticle.setContent(article.getContent());
            homeArticle.setTitle(article.getTitle());
            homeArticle.setTagName(tagName);
            luceneIndexService.addArticleIndex(homeArticle);
        } catch (IOException e) {
            throw new RuntimeException("更新索引失败", e);
        }
        return article;
    }

    /**
     * 更新文章
     *
     * @param article
     * @return
     */
    @Override
    public Article updateArticle(Article article) {
        // 验证文章是否存在
        Article existingArticle = articleMapper.selectArticleById(article.getId());
        if (existingArticle == null) {
            throw new RuntimeException("文章不存在");
        }

        // 验证标签是否存在
        if (article.getTagId() != null) {
            Tag tag = tagMapper.selectTagById(article.getTagId());
            if (tag == null) {
                throw new RuntimeException("标签不存在");
            }
        }

        // 更新文章
        article.setUpdatedAt(String.valueOf(new Date()));
        articleMapper.updateArticle(article);

        // 更新索引
        String tagName=tagMapper.selectNameById(article.getTagId());

        UserProfile userProfile=userProfileMapper.findUserProfileByUserId(article.getAuthorId());

        try {
            // 5. 获取完整聚合数据（文章 + 用户 + 标签）
            ArticleDetailDTO homeArticle = new ArticleDetailDTO();
            homeArticle.setArticleId(article.getId());
            homeArticle.setNickName(userProfile.getNickName());
            homeArticle.setAvatarUrl(userProfile.getAvatarUrl());
            homeArticle.setCreatedAt(article.getCreatedAt());
            homeArticle.setContent(article.getContent());
            homeArticle.setTitle(article.getTitle());
            homeArticle.setTagName(tagName);
            luceneIndexService.updateArticleIndex(homeArticle);
        } catch (IOException e) {
            throw new RuntimeException("更新索引失败", e);
        }
        return articleMapper.selectArticleById(article.getId());
    }

    @Override
    public boolean updateArticleStatus(Long id, Integer status) {
        return articleMapper.updateArticleStatus(id, status) > 0;
    }

    @Override
    public boolean deleteArticle(Long id) {
        Article article = articleMapper.selectArticleById(id);
        if (article == null) {
            return false;
        }

        articleMapper.deleteArticleById(id);

        // 删除索引
        try {
            luceneIndexService.deleteArticleIndex(String.valueOf(id));
        } catch (IOException e) {
            throw new RuntimeException("删除索引失败", e);
        }
        return true;
    }


    @Override
    public boolean isArticleLiked(Long articleId, Long userId) {
        Integer status = articleLikeMapper.getArticleLikeStatus(articleId, userId);
        return status != null && status == 1;
    }


    @Override
    @Transactional
    public boolean likeArticle(Long articleId, Long userId) {
        Integer status = articleLikeMapper.getArticleLikeStatus(articleId, userId);
        if (status != null && status == 1) {
            // 该文章已经点赞过了
            return false;
        }
        if (status == null) {
            // 第一次点赞
            ArticleLike articleLike = new ArticleLike();
            articleLike.setArticleId(articleId);
            articleLike.setUserId(userId);
            articleLike.setStatus(1);
            articleLike.setCreatedAt(new Date());
            articleLikeMapper.insertArticleLike(articleLike);
        } else {
            articleLikeMapper.updateArticleLikeStatus(articleId, userId, 1);
        }
//        articleMapper.incrementArticleLikes(articleId);
        return true;
    }

    @Override
    @Transactional
    public boolean unlikeArticle(Long articleId, Long userId) {
        Integer status = articleLikeMapper.getArticleLikeStatus(articleId, userId);
        // 该文章已经取消点赞过了
        if (status == null || status == 0) {
            return false;
        }
        articleLikeMapper.updateArticleLikeStatus(articleId, userId, 0);
//        articleMapper.decrementArticleLikes(articleId);
        return true;
    }

    @Override
    public List<ArticleLike> selectArticleLikeList(String nickName, String title) {
        return articleLikeMapper.selectArticleLikeList(nickName, title);
    }

    @Override
    public Article getArticleById(Long id) {
        return articleMapper.selectArticleById(id);
    }

    @Override
    public List<Article> getAllArticles() {
        return articleMapper.selectAllArticles();
    }

    @Override
    public List<Article> getArticlesByTag(Long tagId) {
        return articleMapper.selectArticlesByTagId(tagId);
    }

    @Override
    public List<ArticleDetailDTO> getArticleDetails(String tagName, Long authorId) {
        return articleMapper.getArticleDetails(tagName, authorId);
    }

    @Override
    public ArticleDetailDTO getArticleDetail(Long articleId) {
        return articleMapper.getSingleArticleDetail(articleId);
    }

    @Override
    public int updateArticleById(Article article) {
        return articleMapper.updateArticleById(article);
    }


}
